/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.common.security;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.eelpo.common.encoder.BASE64EncoderStream;
import com.eelpo.common.util.BlankUtils;
import com.eelpo.common.util.StringUtils;

/**
 * 功能描述：使用哈希算法信息摘要. 算法推荐使用SHA-1,MD5
 * <p>
 * 版权所有：广州市艾尔博科技有限公司
 * <p>
 * 未经本公司许可，不得以任何方式复制或使用本程序任何部分
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class MessageDigestor {

	// public static final String MD5_ALGORITHM = "MD5";
	// public static final String SHA_ALGORITHM = "SHA";
	// public static final String SHA1_ALGORITHM = "SHA1";
	// public static final String SHA_1_ALGORITHM = "SHA-1";

	/**
	 * <p>
	 * 方法用途和描述：对字节数组进行信息摘要
	 * </p>
	 * 
	 * @param plainBytes
	 *            ：字节数组
	 * @param algorithm
	 *            ：哈希算法
	 * @return 返回信息摘要字节数组
	 * @throws NoSuchAlgorithmException
	 */
	public static byte[] digest(byte[] plainBytes, String algorithm) throws NoSuchAlgorithmException {

		if (BlankUtils.isBlank(plainBytes) || BlankUtils.isBlank(algorithm)) {
			return new byte[] {};
		}

		MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
		messageDigest.update(plainBytes);
		return messageDigest.digest();

	}

	/**
	 * <p>
	 * 方法用途和描述：对字符串进行信息摘要
	 * </p>
	 * 
	 * @param plainText
	 *            ：字符串
	 * @param algorithm
	 *            ：哈希算法
	 * @return 返回信息摘要
	 * @throws NoSuchAlgorithmException
	 */
	public static String digest(String plainText, String algorithm) throws NoSuchAlgorithmException {

		if (BlankUtils.isBlank(plainText) || BlankUtils.isBlank(algorithm)) {
			return StringUtils.EMPTY;
		}

		byte[] cipherBytes = digest(plainText.getBytes(), algorithm);
		return BASE64EncoderStream.encode(cipherBytes);

	}

	/**
	 * <p>
	 * 方法用途和描述：对文件进行信息摘要
	 * </p>
	 * 
	 * @param inputPath
	 *            ：源文件路径
	 * @param outputPath
	 *            ：信息摘要输出文件路径
	 * @param algorithm
	 *            ：哈希算法
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */
	public static void digest(String inputPath, String outputPath, String algorithm) throws NoSuchAlgorithmException, IOException {

		MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
		InputStream inputStream = new BufferedInputStream(new FileInputStream(inputPath));

		for (int i = inputStream.read(); i != -1; i = inputStream.read())
			messageDigest.update((byte) i);
		inputStream.close();
		byte[] digestText = messageDigest.digest();

		FileOutputStream outputStream = new FileOutputStream(outputPath);
		outputStream.write(digestText);

		outputStream.close();
	}
}
